<template>
  <view class="bg-white min-h-100vh p-4">
    <u-form
      label-position="left"
      ref="uForm"
      :model="formData"
      :rules="rules"
      label-width="80"
    >
      <u-form-item
        label="采购类型"
        prop="Category"
        border-bottom
        required
        @click="showThingType = true"
      >
        <picker
          :show="showThingType"
          :range="thingType"
          range-key="label"
          header-text="请选择采购类型"
          @change="handleSelectLeaveType"
        >
          <u-input
            v-model="formData.Category"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择采购类型"
            border="none"
          ></u-input>
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="采购时间"
        prop="Date"
        border-bottom
        required
        @click="calendarShow = true"
      >
        <!-- <picker
          mode="date"
          header-text="请选择值班日期"
          @change="handleSelectDate"
        > -->
        <u-input
          v-model="formData.Date"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择期望采购时间"
          border="none"
        ></u-input>
        <!-- </picker> -->
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>

      <u-form-item label="金额" prop="Amount" border-bottom required>
        <view class="mt-6px">
          <u-input
            v-model="formData.Amount"
            type="number"
            disabledColor="#ffffff"
            placeholder="请输入"
            border="none"
          ></u-input>
        </view>
      </u-form-item>
      <u-form-item
        label="说明"
        prop="Description"
        border-bottom
        required
        label-position="top"
      >
        <view class="mt-6px">
          <u-textarea
            v-model="formData.Description"
            type="textarea"
            disabledColor="#ffffff"
            placeholder="请输入（如商品链接）"
          ></u-textarea>
        </view>
      </u-form-item>
    </u-form>
    <view>
      <u-button
        text="提交"
        color="#386ee8"
        class="mt-10px"
        :throttle-time="600"
        :loading="btnLoading"
        @click="handleSubmit"
      />
    </view>
    <u-calendar
      ref="calendar"
      :show="calendarShow"
      closeOnClickOverlay
      @confirm="handleSelectDate"
      @close="
        () => {
          calendarShow = false
        }
      "
    ></u-calendar>

    <u-divider text="采购记录"></u-divider>
    <view v-if="dataList.length">
      <view
        v-for="i in dataList"
        :key="i.ExpenditureID"
        class="rounded-4px text-first text-14px p-10px -mx-15px"
        style="border-bottom: 1px #ccc solid"
      >
        <view class="flex">
          <text>姓名：{{ i.OfficerName }}</text>
          <text class="mx-20px">类型：{{ i.Category }}</text>
          <text
            class="flex-1 text-right"
            :style="{
              color: i.Color
            }"
          >
            {{ i.Status }}
          </text>
          <u-icon
            v-if="i.status === 'Pending' && userInfo.Permission === 'admin'"
            name="edit-pen-fill"
            size="18"
            @click="handleExamine(i.ExpenditureID)"
          ></u-icon>
        </view>
        <view class="my-10px">金额：￥{{ i.Amount }}</view>
        <view class="my-10px">时间：{{ i.Date }}</view>
        <view style="line-height: 18px">说明：{{ i.Description }}</view>
      </view>
    </view>
    <u-empty v-else mode="data" />
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import dayjs from 'dayjs'
import {
  getPurchaseRecordsApi,
  postPurchaseApi,
  putPurchaseApi
} from './service'
import { showModal, showToast } from '@/utils'
import { userStore } from '@/store'

@Component({ name: 'Purchase' })
export default class OnGuard extends Vue {
  get userInfo(): any {
    return userStore.userInfo || {}
  }
  btnLoading = false
  readonly thingType = [
    {
      label: '设备',
      value: 'Equipment'
    },
    {
      label: '车辆',
      value: 'Vehicles'
    },
    {
      label: '办公',
      value: 'Office'
    }
  ]
  showThingType = false
  calendarShow = false
  rules = {
    Category: {
      type: 'string',
      required: true,
      message: '请选择采购类型',
      trigger: ['blur', 'change']
    },
    Date: {
      type: 'string',
      required: true,
      message: '期望采购时间',
      trigger: ['change']
    },
    Amount: {
      type: 'string',
      required: true,
      message: '请输入金额',
      trigger: ['blur']
    },
    Description: {
      type: 'string',
      required: true,
      message: '请选择采购说明',
      trigger: ['blur']
    }
  }
  formData = {
    OfficerID: this.userInfo.OfficerID,
    Amount: null,
    Category: '',
    Date: '',
    Description: '',
    Status: 'Pending' //Approved,Rejected,Pending
  }

  handleSelectLeaveType({ detail: { value } }: any) {
    this.formData.Category = String(this.thingType[value].label)
    this.showThingType = false
  }
  handleSelectDate([date]: string[]) {
    this.formData.Date = date
    this.calendarShow = false
  }
  async handleSubmit() {
    try {
      await (this.$refs.uForm as any).validate()
      uni.showLoading({ title: '加载中...' })
      await postPurchaseApi({
        ...this.formData,
        Category: this.thingType.find((i) => i.label === this.formData.Category)
          ?.value
      })
      await showToast({ title: '提交成功' })
      this.formData = {
        OfficerID: this.userInfo.OfficerID,
        Amount: null,
        Category: '',
        Date: '',
        Description: '',
        Status: 'Pending'
      }
      await this.getData()
    } finally {
      uni.hideLoading()
    }
  }

  async handleExamine(ExpenditureID: string) {
    const { confirm } = await showModal({
      title: '是否通过采购申请？',
      cancelColor: '#ff0000',
      confirmColor: '#409eff',
      cancelText: '拒绝',
      confirmText: '通过'
    })
    try {
      uni.showLoading({
        title: '加载中'
      })
      await putPurchaseApi({
        ExpenditureID,
        Status: confirm ? 'Approved' : 'Rejected'
      })
      this.getData()
    } finally {
      uni.hideLoading()
    }
  }

  dataList: Recordable = []
  async getData() {
    const { OfficerID, Permission }: any = userStore.userInfo ?? {}
    const { records } = await getPurchaseRecordsApi({
      OfficerID: Permission === 'user' ? OfficerID : ''
    })
    this.dataList = records.map((o: any) => {
      return {
        ...o,
        Category: this.thingType.find((l) => l.value === o.Category)?.label,
        Date: dayjs(o.Date).format('YYYY-MM-DD'),
        status: o.Status,
        Status:
          o.Status === 'Pending'
            ? '审批中'
            : o.Status === 'Approved'
            ? '通过'
            : '拒绝',
        Color:
          o.Status === 'Pending'
            ? '#F9AE3D'
            : o.Status === 'Approved'
            ? '#5AC725'
            : '#F56C6C'
      }
    })
  }
  async onLoad() {
    await this.getData()
  }
}
</script>

<style lang="scss" scoped></style>
